<template>
    <div class="ups">
        <div v-for="(item,index) in obj.fileurls" :key="item" class="fileDiv">
            <img v-if="item.fileUrl && item.isImg" :src="item.fileUrl" class="avatar" />
            <span v-if="item.fileUrl && !item.isImg" class="avatar-uploader-file"><span>{{item.name}}</span></span>
            <span v-if="!item.fileUrl" class="up_uploading">上传中...</span>
            <span class="up_del" v-show="item.fileUrl" @click="del(index)"></span>
            <div class="progress" v-show="item.progressFlag">
                <span><u :style="'width:'+item.loadProgress"></u></span>
                <i>{{item.loadProgress}}</i>
            </div>
        </div>
        <div class="upDiv">
            <span class="avatar-uploader"></span>
            <input type="file" :accept="accept" multiple="multiple" webkitdirectory @change="upfile" v-if="props.candir" />
            <input type="file" :accept="accept" multiple="multiple" @change="upfile" v-else />
        </div>
    </div>
</template>

<script setup>
    import { reactive, getCurrentInstance, watch } from 'vue'
    let { proxy } = getCurrentInstance()
    const emit = defineEmits(['update:files','update:filesizes']) //此处要完全对应，采用固定的update:prop属性
    const imgTypes = ['jpg','jpeg','png','gif','webp']
    let isUpload = false //默认没上传过

    const props = defineProps({
        accept: { type: Array, default: ['image/jpeg','image/png','image/gif','image/webp'] }, //'application/vnd.ms-excel','application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
        debug: { type: Boolean, default: false },
        candir: { type: Boolean, default: false },
        old_files: { type: String, default: "", require: true },
        files: { type: String, default: "", require: true },
        filesizes: { type: String, default: "", require: true },
        dir: { type: String, default: "" },
        rename: { type: Boolean, default: true }, //默认要改名
        maxlength: { type: Number, default: 0 }, //默认0，不限制
        maxsize: { type: Number, default: 1024 * 1024 * 5 }, //单位K，默认5120K，即5M
        maxwidth: { type: Number, default: 0 },
        maxheight: { type: Number, default: 0 },
        background: { type: String, default: "" },
    })
    let init = val => {
        return val.split(",").filter(t => t!="").map(t => {
            let tmp = {
                id: Math.random(),
                name: t,
                progressFlag: false,
                loadProgress: "0%",
                fileUrl: "",
                isImg: t=="" ? "" : imgTypes.some(p => p === t.split('.').pop().toLowerCase())
            }
            tmp.fileUrl = `${proxy.$setting.globalUrl.fileurl}/${props.dir}/${t}`
            // if (!isUpload && t != "")
            //     tmp.fileUrl = `${proxy.$setting.globalUrl.fileurl}/${props.dir}/${t}`
            // if (isUpload && t != "")
            //     tmp.fileUrl = `${proxy.$setting.globalUrl.upload}/${t}`
            return tmp
        })
    }
    let obj = reactive({
        innerFiles: props.files.split(",").filter(t => t != ""),
        innerFilesizes: props.filesizes.split(",").filter(t => t != ""),
        fileurls: init(props.files),
    })
    watch(
        () => props.old_files,
        (val) => {
            obj.innerFiles = val.split(",").filter(t => t!="")
            obj.fileurls = init(val)
        },
        // { immediate: true, deep: true } //immediate表示第一次就输出，默认是false；deep表示深度监听，能监听到对像的内容变化
    )

    let del = i => {
        obj.innerFiles.splice(i,1)
        obj.innerFilesizes.splice(i,1)
        obj.fileurls.splice(i,1)
        emit('update:files', obj.innerFiles.join())
        emit('update:filesizes', obj.innerFilesizes.join())
        // emit('update:files', obj.fileurls.map(t => t.name))
    }
    let upfile = e => {
        let files = []
        for(let i=0; i<e.srcElement.files.length; i++){
            files.push(e.srcElement.files[i])
        }
        // console.log(files)
        files.forEach(file => {
            if (props.debug) console.log(file.type)
            let isType = props.accept.some(t => t === file.type)
            if (file.type == "") isType = true //如果就没拿到file.type（这是有可能的），就认为是过
            if (props.accept.length <= 0) isType = true //如果没格式要求，也认为是过
            let isLimit = file.size < props.maxsize

            if (!isType) {
                proxy.elMessageMixin(`${file.type}格式不正确`, 'error')
                return
            }
            if (!isLimit) {
                proxy.elMessageMixin(`${file.name}超过${props.maxsize/(1024*1024)}M`, 'error')
                return
            }

            //检查完成，可以上传
            const curItem = Math.random()
            let upItem = {
                id: curItem,
                name: file.name,
                progressFlag: true,
                loadProgress: "0%",
                // fileUrl: "", //不给，到完成再给，这样上面就能判断了
                isImg: imgTypes.some(p => p === file.name.split('.').pop().toLowerCase())
            }
            obj.fileurls.push(upItem) //加到前面
            let formData = new FormData(); //这样可以给form参数了
            formData.append("type", file.type);
            formData.append("file", file);
            formData.append("rename", props.rename ? 0 : 1);
            if (props.candir) formData.append("webkitRelativePath", file.webkitRelativePath);
            if (props.maxwidth > 0) formData.append("maxheight", props.maxwidth);
            if (props.maxheight > 0) formData.append("maxwidth", props.maxheight);
            if (props.background != "") formData.append("background", props.background);

            proxy.$ajax({
                baseURL: "",
                url: proxy.$setting.globalUrl.uploadserver,
                data: formData,
                isUploadFile: true,
                bfLoading: false,
                timeout: 0,
                progress: p => {
                    obj.fileurls.find(t => t.id==curItem).loadProgress = (p.loaded / p.total * 100 | 0) + '%' //这里不能直接用upItem，因为实际上这时还没绑上去，即指向还未生效
                }
            }).then(res => {
                let tmpItem = obj.fileurls.find(t => t.id==curItem)
                tmpItem.fileUrl = `${proxy.$setting.globalUrl.upload}/${res.filename}`
                tmpItem.name = res.filename
                obj.innerFiles.push(res.filename)
                obj.innerFilesizes.push(res.filesize)
                // emit('update:files', obj.fileurls.map(t => t.name))
                emit('update:files', obj.innerFiles.join())
                emit('update:filesizes', obj.innerFilesizes.join())
                tmpItem.progressFlag = false
            }).catch((() => {
                obj.fileurls.find(t => t.id==curItem).progressFlag = false
                // obj.fileurls.remove(upItem) //删掉之前加的
            }))
        });
    }
</script>

<style scoped lang="scss">
    $w: 120px;
    $h: 120px;
    $color: #d8dae2;
    .ups { display: flex; flex-wrap: wrap; 
        .avatar-uploader, .avatar-uploader-file, .up_uploading { position: relative; width: $w; height: $h; overflow: hidden; background-color: #FFF; border: 1px solid $color; box-sizing: border-box; display: flex; justify-content: center; align-items: center; }
        .fileDiv { margin-right: 5px; margin-bottom: 5px; position: relative; 
            .avatar { width: $w; height: $h; object-fit: contain; box-sizing: border-box; border: 1px solid $color; }
            .avatar-uploader-file {
                span { position: absolute; bottom: 0; font-size: 12px; line-height: 14px; text-align: center; }
                &::after { content:'\e6b7'; font-family: "iconfont"; opacity: .4; font-size: 40px; }
            }
            .up_del { position: absolute; top: 0; right: 6px; 
                &::after { content: "\e74b"; font-family: "iconfont"; font-size: 10px; }
            }
            .up_uploading { font-size:12px; }
            .progress { display: flex; width:120px; margin-top: 3px; align-items: center; 
                * { display: flex; font-style: normal; font-size: 12px; }
                span { flex: 1; align-items: center; height:6px; border-radius: 3px; background-color: $color; margin-right: 5px; }
                u { background-color: #3a4fbd; height:6px; border-radius: 3px; }
            }
        }
        .upDiv { position: relative; width: $w; height: $h+20; overflow: hidden; 
            input { position: absolute; top:-20px; font-size:0; appearance:none; width: $w; height: $h+20; }
            .avatar-uploader::after { content:'\e626'; font-family: "iconfont"; font-size: 40px; color: $color; }
        }
    }
</style>